package com.uinnova.product.eam.model.dm.bean;

import com.binary.core.util.BinaryUtils;
import com.binary.framework.bean.annotation.Comment;
import com.uinnova.product.eam.base.exception.ServerException;
import com.uinnova.product.eam.model.dm.DataModelAttribute;
import com.uino.bean.cmdb.base.ESCIInfo;
import lombok.Data;

import java.util.Map;

/**
 * 数据建模生成DDL实体属性
 * @author ch
 */
@Data
public class DataModelAttributeVo {
    @Comment("字段英文名")
    private String name;
    @Comment("字段中文名")
    private String comment;
    @Comment("类型")
    private String type;
    @Comment("长度")
    private String length;
    @Comment("精度")
    private String precision;
    @Comment("非空")
    private Boolean notEmpty = false;
    @Comment("主键")
    private Boolean pk = false;

    @Comment("默认值")
    private String defaultVal;

    public DataModelAttributeVo(String entityName, ESCIInfo ci, Map<String, String> dataTypeMap){
        Map<String, Object> attrs = ci.getAttrs();
        if(!BinaryUtils.isEmpty(attrs.get(DataModelAttribute.NAME_EN))){
            this.name = attrs.get(DataModelAttribute.NAME_EN).toString().toUpperCase();
        }else{
            throw new ServerException(errorMsg(entityName, "英文名称"));
        }
        if(!BinaryUtils.isEmpty(attrs.get(DataModelAttribute.NAME_CN))){
            this.comment = attrs.get(DataModelAttribute.NAME_CN).toString().toUpperCase();
        }else{
            throw new ServerException(errorMsg(entityName, "中文名称"));
        }
        if(!BinaryUtils.isEmpty(attrs.get(DataModelAttribute.DATA_TYPE))){
            String dataType = attrs.get(DataModelAttribute.DATA_TYPE).toString();
            if(BinaryUtils.isEmpty(dataTypeMap.get(dataType))){
                this.type = dataType.toUpperCase();
            }else{
                this.type = dataTypeMap.get(dataType).toUpperCase();
            }
        }else{
            throw new ServerException(errorMsg(entityName, "数据类型"));
        }
        if(!BinaryUtils.isEmpty(attrs.get(DataModelAttribute.LENGTH))){
            this.length = attrs.get(DataModelAttribute.LENGTH).toString();
        }
        if(!BinaryUtils.isEmpty(attrs.get(DataModelAttribute.PRECISION))){
            this.precision = attrs.get(DataModelAttribute.PRECISION).toString();
        }
        if(!BinaryUtils.isEmpty(attrs.get(DataModelAttribute.NON_EMPTY))){
            this.notEmpty = Boolean.parseBoolean(attrs.get(DataModelAttribute.NON_EMPTY).toString());
        }
        if(!BinaryUtils.isEmpty(attrs.get(DataModelAttribute.PRIMARY_KEY))){
            this.pk = Boolean.parseBoolean(attrs.get(DataModelAttribute.PRIMARY_KEY).toString());
        }
        if(!BinaryUtils.isEmpty(attrs.get(DataModelAttribute.DEFAULT_VAL))){
            this.defaultVal = attrs.get(DataModelAttribute.DEFAULT_VAL).toString();
        }
    }

    private static String errorMsg(String entityName, String field){
        return "请填写完整【"+entityName+"】中实体属性【"+field+"】!";
    }
}
